package pro.ticktock.tools.mbconv;

import java.io.*;

/*
 * Author: lambo
 * Date: 2018-09-20
 */
public abstract class AbstractPass implements Pass{
  protected final String origSrcFileName;
  protected final String srcFileName;
  protected String srcFileNameNoExt;
  protected String ext;

  protected final BufferedWriter resultWriter;
  protected final BufferedWriter logWriter;
  protected final BufferedReader srcReader;

  protected static String rootDir = MusciBibleConverter.getRootDir();

  protected AbstractPass(String srcFileName) throws IOException {
    this(srcFileName, srcFileName);
  }

  protected AbstractPass(String origSrcFileName, String srcFileName) throws IOException {
    this.origSrcFileName = origSrcFileName;
    this.srcFileName = srcFileName;

    int idx = origSrcFileName.lastIndexOf('.');
    if (idx >= 0) {
      srcFileNameNoExt = origSrcFileName.substring(0, idx);
      ext = origSrcFileName.substring(idx + 1);
    } else {
      srcFileNameNoExt = origSrcFileName;
      ext = "";
    }
    resultWriter =
            new BufferedWriter(new FileWriter(new File(getFullName(getResultFileName()))));
    logWriter =
            new BufferedWriter(new FileWriter(new File(getFullName(getLogFileName()))));
    srcReader = new BufferedReader(new FileReader(getFullName(srcFileName)));
  }

  public String getResultFileName() {
    return srcFileNameNoExt + "." + name() + "." + ext;
  }

  public String getLogFileName() {
    return srcFileNameNoExt + "." + name() + ".log";
  }

  public String getFullName (String fileName) {
    return rootDir + fileName;
  }

  public static void setRootDir(String dir) {
    rootDir = dir;
  }

  protected void preProcess() throws IOException {}

  protected void postProcess() throws IOException {}

  public void process() {
    try {
      preProcess();
      doProcess();
      postProcess();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    } finally {
      try {
        resultWriter.close();
        logWriter.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public String trim(String line) {
    char[] value = line.toCharArray();
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */

    while ((st < len) && ((val[st] <= ' ') || val[st] == '　')) {
      st++;
    }
    while ((st < len) && ((val[len - 1] <= ' ') || (val[len - 1] == '　'))) {
      len--;
    }
    return ((st > 0) || (len < value.length)) ? line.substring(st, len) : line;
  }

  protected abstract void doProcess() throws IOException;

  public String name() {
    return getClass().getSimpleName().toLowerCase();
  }
}
